package helperfunctions

import (
	"errors"
	"time"

	"github.com/golang-jwt/jwt"
)

type tokenClaims struct {
  jwt.StandardClaims
  UserId string `json:"id"`
}

const (
  tokenTLL = 12 * time.Hour
  signinKey = "ewklj.23#8974keqwqwe#bmxvcSS+_.#"
)

func GenerateToken(id string) (string, error) {
  token := jwt.NewWithClaims(jwt.SigningMethodHS256, &tokenClaims{
    jwt.StandardClaims {
      ExpiresAt:time.Now().Add(tokenTLL).Unix(),
      IssuedAt: time.Now().Unix(),
    },
    id,
  })

  return token.SignedString([]byte(signinKey))
}

func ParseToken(accessToken string) (string, error) {
  token, err := jwt.ParseWithClaims(accessToken, &tokenClaims{}, func(token *jwt.Token) (interface{}, error) {
    if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
      return nil, errors.New("invalid signin method")
    }

    return []byte(signinKey), nil
  })

  if err != nil {
    return "", err
  }

  claims, ok := token.Claims.(*tokenClaims)

  if !ok {
    return "", errors.New("token claims are not of type")
  }

  return claims.UserId, nil
}
